{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 研究位置\n",
    "server.py  -> websocket_endpoint\n",
    "```python\n",
    "@app.websocket(\"/ws\")\n",
    "async def websocket_endpoint(websocket: WebSocket):\n",
    "    await manager.connect(websocket)\n",
    "    try:\n",
    "        await handle_websocket_communication(websocket, manager)\n",
    "    except WebSocketDisconnect:\n",
    "        await manager.disconnect(websocket)\n",
    "\n",
    "```\n",
    "\n",
    "# WebSocket 通信流程图\n",
    "\n",
    "\n",
    "![websocket通信流程图](../images/image11112.png)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "\n",
    "## 流程说明\n",
    "\n",
    "1. **连接建立**：前端通过 WebSocket 协议连接到后端端点\n",
    "2. **连接注册**：后端调用 `manager.connect()` 注册新连接\n",
    "3. **发送研究请求**：前端发送带前缀的研究请求\n",
    "4. **接收消息**：后端通过 `websocket.receive_text()` 接收消息\n",
    "5. **前缀检查**：检查消息是否以 \"start\" 开头\n",
    "6. **命令处理**：调用 `handle_start_command()` 处理研究请求\n",
    "7. **启动流式任务**：调用 `manager.start_streaming()` 启动研究\n",
    "8. **执行研究**：调用 `run_agent()` 执行实际研究任务\n",
    "9. **进度推送**：研究进度实时推送到前端\n",
    "10. **报告推送**：最终研究报告推送到前端\n",
    "11. **聊天请求**：前端发送聊天消息\n",
    "12. **聊天处理**：后端调用 `handle_chat()` 处理聊天\n",
    "13. **聊天回复**：聊天回复推送到前端\n",
    "14. **连接关闭**：前端关闭 WebSocket 连接\n",
    "15. **连接清理**：后端调用 `manager.disconnect()` 清理资源\n",
    "\n",
    "这个流程展示了从连接建立到研究任务执行再到聊天互动的完整 WebSocket 通信过程。🙂"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
